package com.weiqiao.report.distributior.Service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.weiqiao.report.distributior.Service.IUserReportService;
import com.weiqiao.report.distributior.domain.AccountDetailReportEntity;
import com.weiqiao.report.distributior.domain.dto.UserReportEntityDTO;
import com.weiqiao.report.distributior.domain.vo.UserReportVO;
import com.weiqiao.report.distributior.repository.IAccountDetailReportRepository;
import com.weiqiao.report.distributior.repository.IUserRepository;
import com.weiqiao.report.util.MemberTypeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("ReportUserReportServiceImpl")
public class UserReportServiceImpl implements IUserReportService {

    @Autowired
    private IUserRepository userRepository;

    @Autowired
    private IAccountDetailReportRepository accountDetailReportRepository;

    @Override
    public List<UserReportEntityDTO> getUserList(UserReportVO vo, Pageable pageable) {
        Integer company_id = vo.getCompany_id();
        Document doc = this.getUserFilter(vo); // 查询条件
        List<String> list = userRepository.getPage(company_id, doc, pageable);
        return this.getListToEntity(company_id, list);
    }

    private Document getUserFilter(UserReportVO vo) {
        Document doc = new Document();
        // 默认会员类型大于0， 分销员统计大于0
        doc.append("member_type", new Document("$gt", 0));
        if (!StringUtils.isBlank(vo.getKeywords())) {  // 手机号 微信昵称
            List<Document> List = new ArrayList<>();
            List.add(new Document("phone", new Document("$regex", vo.getKeywords())));
            List.add(new Document("nickname", new Document("$regex", vo.getKeywords())));
            doc.append("$or", List);
        }
        if (null != vo.getMember_type()) {
            doc.append("member_type", vo.getMember_type()); //等级 0:客户  1：分销员  2：团长  3：省长
        }
        if (!StringUtils.isBlank(vo.getUser_ids())) {
            String[] strL = vo.getUser_ids().split(",");  // 接受数组 切割为字符串
            int[] intL = new int[strL.length];
            for (int i = 0; i < intL.length; i++) {
                intL[i] = Integer.parseInt(strL[i]);
            }
            List<Integer> listI = Arrays.stream(intL).boxed().collect(Collectors.toList());
            doc.append("user_id", new Document("$in", listI));
        }
        return doc;
    }

    /**
     * 从数据库拿到的数据转实体类
     * @param list
     * @return
     */
    private List<UserReportEntityDTO> getListToEntity(int companyId, List<String> list) {
        List<UserReportEntityDTO> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            Gson gson = new Gson();
            for (String info : list) {
                UserReportEntityDTO userReportEntityDTO = gson.fromJson(info, UserReportEntityDTO.class);
                // 获取未结算的订单数，佣金
                Bson filter = new Document("result_type", 0).append("user_id", userReportEntityDTO.getUser_id());
                this.getAccountDetailInfo(companyId, filter, userReportEntityDTO);
                // 累计订单，累计佣金 = 待结算 + 已结算
                userReportEntityDTO.setTotal_order(userReportEntityDTO.getBe_settled_order() + userReportEntityDTO.getSettled_order());
                userReportEntityDTO.setTotal_commission(userReportEntityDTO.getBe_settled_commission() + userReportEntityDTO.getSettled_commission());
                // 存储
                result.add(userReportEntityDTO);
            }
        }
        return result;
    }

    private void getAccountDetailInfo(int companyId, Bson filter, UserReportEntityDTO userReportEntityDTO) {
        List<String> accountArray = accountDetailReportRepository.getList(companyId, filter);
        if (CollectionUtils.isNotEmpty(accountArray)) {
            Gson gson = new Gson();
            userReportEntityDTO.setBe_settled_order(accountArray.size());
            for (String info: accountArray) {
                AccountDetailReportEntity entity = gson.fromJson(info, AccountDetailReportEntity.class);
                userReportEntityDTO.setBe_settled_commission(userReportEntityDTO.getBe_settled_commission() + entity.getAccount_money());
            }
        }
    }

    @Override
    public int countNum(UserReportVO vo) {
        Integer company_id = vo.getCompany_id();
        Document doc = this.getUserFilter(vo);
        return userRepository.countFruiter(company_id, doc);
    }

    @Override
    public List<Map<String, Object>> expportUserList(UserReportVO vo) {
        List<Map<String, Object>> export = new ArrayList<>();
        Document doc = this.getUserFilter(vo);
        int company_id = vo.getCompany_id();
        List<String> list = userRepository.getAppUserByFilterSortSkipLimit(doc, new Document("settled_commission", -1), 0, 1000, company_id);
        List<UserReportEntityDTO> array = this.getListToEntity(company_id, list);
        if (CollectionUtils.isNotEmpty(array)) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            for (UserReportEntityDTO info: array) {
                if (StringUtil.isLong(info.getCreate_time())) {
                    info.setCreate_time(simpleDateFormat.format(Long.parseLong(info.getCreate_time())));
                }
                export.add(ExcelContent(info));
            }
        }
        return export;
    }

    public Map<String, Object> ExcelContent(UserReportEntityDTO user) {
        Map map = new LinkedHashMap();
        map.put("手机号码", user.getPhone());
        map.put("微信昵称", user.getNickname());
        map.put("姓名", user.getUser_name());
        map.put("等级角色", MemberTypeUtil.getMemberType(user.getMember_type()));
        map.put("累计订单", user.getTotal_order());
        map.put("累计佣金", user.getTotal_commission());
        map.put("待结算订单", user.getBe_settled_order());
        map.put("待结算佣金", user.getBe_settled_commission());
        map.put("已结算订单", user.getSettled_order());
        map.put("已结算佣金", user.getSettled_commission());
        return map;
    }


}
